package it.koutifaris.travianmap.ui.viewstate;

import it.koutifaris.travianmap.context.HasApplicationContex;
import it.koutifaris.travianmap.dal.MapServiceFactory;
import it.koutifaris.travianmap.dal.MapUIService;
import it.koutifaris.travianmap.dal.MapUIService.MapViewState;
import it.koutifaris.travianmap.dal.TravianServerService.TravianServer;
import it.koutifaris.travianmap.ui.DynamicViewStateToViewState;

public class ViewStatePersister extends HasApplicationContex {

	private final TravianServer travianServer;

	public ViewStatePersister(TravianServer travianServer) {
		this.travianServer = travianServer;
	}

	public DynamicViewState loadViewStateFromDB() {
		DynamicViewState result;

		if (travianServer == null) {
			result = ViewStateBuilder.viewStateBuilder()
					.withDefaultSquareSize()
					.build();
		} else {
			MapServiceFactory mapServiceFactory = getTravianMapContext().getMapServiceFactory(travianServer.getServerId());
			MapUIService mapUIService = mapServiceFactory.mapUIService();

			MapViewState savedViewState = mapUIService.readState();

			result = ViewStateBuilder.viewStateBuilder()
					.withDefaultSquareSize()
					.withPosition(savedViewState.getX(), savedViewState.getY())
					.withZoom(savedViewState.getZoom()).build();

			mapUIService.close();
		}

		return result;
	}

	public void saveViewState(DynamicViewState viewState) {
		if (travianServer != null) {
			MapServiceFactory mapServiceFactory = getTravianMapContext().getMapServiceFactory(travianServer.getServerId());
			MapUIService mapUIService = mapServiceFactory.mapUIService();
			mapUIService.writeState(new DynamicViewStateToViewState(viewState));
			mapUIService.close();
		}
	}

}
